/*
 * VerificationDialog.java
 *
 * Created on __DATE__, __TIME__
 */

package clientPresentation;

import javax.swing.JOptionPane;

import utils.Base64Processing;

import messages.CompetenceValidationResponseMessage;
import messages.CompetenceValidationRequestMessage;
import messages.NonceToSignRequestMessage;
import messages.NonceToSignResponseMessage;
import client.ClientData;
import client.exceptions.SocketUninitializedException;
import connection.CitizenCardInterface;
import connection.exception.CardErrorException;
import connection.exception.ConnectionResetException;

/**
 *
 * @author  __USER__
 */
@SuppressWarnings("serial")
public class VerificationDialog extends javax.swing.JDialog {

    /** Creates new form VerificationDialog */
    public VerificationDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    //GEN-BEGIN:initComponents
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        competenceField = new javax.swing.JTextField();
        competenceLabel = new javax.swing.JLabel();
        verifyButton = new javax.swing.JButton();

        setTitle("Inserir Compet\u00eancia");
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        competenceField.setText("PresidenteIST");

        competenceLabel.setText("Compet\u00eancia");

        verifyButton.setText("Verificar");
        verifyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(competenceLabel)
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(verifyButton)
                                                .addComponent(
                                                        competenceField,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        121,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap(44, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(
                                        layout.createParallelGroup(
                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(competenceLabel)
                                                .addComponent(
                                                        competenceField,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(
                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(verifyButton)
                                .addContainerGap(
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)));

        pack();
    }// </editor-fold>
    //GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

        try {
            
            // TODO Get the first and last name from the CC
            String[] fullName = CitizenCardInterface.getFirstLastName();
            String fname = fullName[0];
            String lname = fullName[1];
            String competence = competenceField.getText();
            
            // Send the first protocol message, asking for the nonce
            NonceToSignRequestMessage msg = new NonceToSignRequestMessage(fname, lname, competence);
            ClientData.getInstance().send(msg);

            // Receive the message containing the nonce
            NonceToSignResponseMessage res = (NonceToSignResponseMessage) ClientData.getInstance().receive();

            // Get the nonce and sign it
            Integer nonce = res._nonce;
            String valueToSign = nonce + competence;
            String signature = Base64Processing.encodeData(CitizenCardInterface.SignData(valueToSign));
            
            // Send the nonce, Signature and Competence
            CompetenceValidationRequestMessage val = 
                new CompetenceValidationRequestMessage(competence, nonce, signature);
            ClientData.getInstance().send(val);
            
            // Receive the message containing the result
            CompetenceValidationResponseMessage resp =  
                (CompetenceValidationResponseMessage) ClientData.getInstance().receive();
            boolean result = resp._result;
            
            
            // Mostrar Diálogo com resultado
            JOptionPane.showMessageDialog(this, "A competência é "
                    + (result ? "válida" : "inválida"));
        } catch (ConnectionResetException e) {
            e.printStackTrace();
        } catch (SocketUninitializedException e) {
            e.printStackTrace();
        } catch (CardErrorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                VerificationDialog dialog = new VerificationDialog(
                        new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    //GEN-BEGIN:variables
    // Variables declaration - do not modify
    private javax.swing.JTextField competenceField;

    private javax.swing.JLabel competenceLabel;

    private javax.swing.JButton verifyButton;
    // End of variables declaration//GEN-END:variables

}